package cn.edu.njnu.opengmpback.recommendation.client;

import cn.edu.njnu.opengmpback.recommendation.client.dto.DifyWorkflowRequest;
import cn.edu.njnu.opengmpback.recommendation.client.dto.DifyWorkflowResponse;
import cn.edu.njnu.opengmpback.recommendation.config.DifyConfig;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

@Component
@RequiredArgsConstructor
@Slf4j
public class DifyApiClient {
    private final DifyConfig difyConfig;
    public DifyWorkflowResponse executeWorkflow(DifyWorkflowRequest request) {
        try {
            RestTemplate restTemplate = new RestTemplate();

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setBearerAuth(difyConfig.getKey());

            headers.set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36");


            // 创建请求实体
            HttpEntity<DifyWorkflowRequest> entity = new HttpEntity<>(request, headers);

            log.info("调用Dify工作流API: {}", entity);

            // 发送请求
            ResponseEntity<DifyWorkflowResponse> response = restTemplate.postForEntity(
                    difyConfig.getUrl(),
                    entity,
                    DifyWorkflowResponse.class
            );

            log.info("Dify API调用成功，状态: {}", response.getStatusCode());
            return response.getBody();

        } catch (RestClientException e) {
            log.error("调用Dify API失败", e);
            throw new RuntimeException("推荐服务调用失败", e);
        }
    }


}
